package com.pb.camera;


import java.util.Map;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.application.App;
import com.pb.camera.utils.Constants;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.uniqueID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


public class LoadActivity  extends Activity{
	private String logs;	
	private String account;
	private  String password;
	private 	HttpUtils httpUtils = new HttpUtils(); 
	private  Handler  handle=new Handler()
	{
	  public void handleMessage(android.os.Message msg) {
		  
		   if (msg.what==0) {
			   default_log();
		}	  
	  };	
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.load_activity);
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
	           getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	       }
	    App.getInstance().getAllActivity().add(this);
	    SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);  
   	    String welcome=pre.getString("welcomed", "default");
   	    //若是刚刚下载app第一次登陆的话,进入引导界面
//   	    if (welcome.equals("default")) {
//   	    	Bundle bundle=new Bundle();
//   	    	bundle.putInt("mode", 0);
//   			Intent  inte=new Intent(this,LogInActivity.class);
//   			inte.putExtras(bundle);
//   			startActivity(inte);
//   			Editor  ed=pre.edit();
//   			ed.putString("welcomed", "true");
//   			ed.commit();
//   			finish();
//   			return;
//   		}
	    handle.sendEmptyMessageDelayed(0,2000);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		//极光推送,统计,设置别名
//		JPushInterface.onResume(this);
//		JPushInterface.setAlias(getApplicationContext(), App.getInstance().getUserId(), new TagAliasCallback() {
//			
//			@Override
//			public void gotResult(int arg0, String arg1, Set<String> arg2) {
//				switch (arg0) {
//		          case 0:
//		            logs = "Set tag and alias success";
//		            LogUtil.e(LoadActivity.this, logs);
//		            break;
//		          case 6002:
//		            logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
//		            LogUtil.e(LoadActivity.this, logs);
//		            break;
//		          default:
//		            logs = "Failed with errorCode = " + arg0;
//		            LogUtil.e(LoadActivity.this, logs);
//		          }	
//			}
//		});
		super.onResume();
		// 
	}
	   private   void  default_log()
	   {	
		   //必须通过解锁手势的界面
		   //所以手势的密码必须保存
		   SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);  
	   	    String welcome=pre.getString("welcomed", "default");
	   	    //若是刚刚下载app第一次登陆的话,进入引导界面
//	   	    if (welcome.equals("default")) {
//	   	    	Bundle bundle=new Bundle();
//	   	    	bundle.putInt("mode", 0);
//	   			Intent  inte=new Intent(this,SampleCirclesDefault.class);
//	   			inte.putExtras(bundle);
//	   			startActivity(inte);
//	   			Editor  ed=pre.edit();
//	   			ed.putString("welcomed", "true");
//	   			ed.commit();
//	   			finish();
//	   			return;
//	   		}
	   	    //否者的话开始登陆
		    account= pre.getString("account", "default");
		    password= pre.getString("password", "default");   
		    if (account.equals("default")||password.equals("default")) {
		    	Bundle bundle = new Bundle();
				bundle.putString("whereFrom", "load");
				bundle.putString("errorMessage", "0");				
				Intent intent = new Intent(LoadActivity.this,
						LogInActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
			}else {
			    getCode( Constants.login(account, password, uniqueID.id(this),""), this,1);
			}
		    //开始登录
	   }   

		  private  void  updateAppUserInfo(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
		  {		 
			  App application=App.getInstance();
			  application.setAccount(account);
			  application.setPassword(password);
			  application.setOpenId(openId);
			  application.setGesture(gesture);
			  application.setMobile(mobile);
			  application.setEmail(email);
			  application.setUserId(userId);	  
		  }
		  private  void  saveUserMessage(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
		  {			  
		
			  SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);		    		  
		        Editor  editor=pre.edit();
//		        editor.putString("account",account);
//		        //密码不在返回之内列
//		        //自己补充的
//		        editor.putString("password",password);
		        Log.i("123", "load保存密码"+password);
		        Log.i("123", "load保存账号"+account);
		        editor.putString("gesture",gesture);
		        editor.putString("openid",openId);	
		        editor.putString("email",email);	
		        editor.putString("userid",userId);	
		        editor.putString("mobile",mobile);
		        editor.commit();		        
		  }	   
	   /** 自动登录的
	 * @param url
	 * @param activity
	 * @param mode
	 */
	private void getCode(String url, final Activity activity, final int mode) {
		httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Toast.makeText(activity, "网络访问失败,请检查你的网络", 0).show();
			}
			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				boolean flag = JsonAnalyle.jsonAnalyse(arg0.result, null, null,
						null);
				// 返回true
				if (flag) {
					// 使用账户密码登录成功保存最新的账户名
					// 保存的账户密码都是加密完了的,但是openid没有用urlEncode加密
					Map map = JsonAnalyle.logSuccess(arg0.result);
					// gesture=(String) map.get("gesture");
					// userId=(String) map.get("userid");
					// email= (String) map.get("email");
					// mobile=(String) map.get("mobile");
					// openId= (String) map.get("openid");
					updateAppUserInfo((String)map.get("account"), password,
							(String) map.get("gesture"),
							(String) map.get("userid"),
							(String) map.get("email"),
							(String) map.get("mobile"),
							(String) map.get("openid"));
					// 必须调用这个函数
					//解锁activity会从sp文件读取gesture
					saveUserMessage((String)map.get("account"), password,
							(String) map.get("gesture"),
							(String) map.get("userid"),
							(String) map.get("email"),
							(String) map.get("mobile"),
							(String) map.get("openid"));
					Intent intent0 = new Intent();
					intent0.setClass(LoadActivity.this,
							UnlockGesturePasswordActivity.class);
					startActivity(intent0);
					finish();
				} else {
					
					String errcode = JsonAnalyle.getErrcode(arg0.result, null);
					String errorMessage = getErrorMessage(errcode);
					Bundle bundle = new Bundle();
					bundle.putString("whereFrom", "load");
					bundle.putString("errorMessage", errorMessage);
					Intent intent = new Intent(LoadActivity.this,
							LogInActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
					finish();
				}
			}
		});
	}	   
	
	private String getErrorMessage(String errorCode)
	{  
		   if (errorCode.equals("50012")) {
			  return "用户已在其他移动设备登录";
		}else 	   if (errorCode.equals("50007")) {
			  return "账号或密码不正确";
		}else 	   if (errorCode.equals("50015")) {
			  return "此账户已绑定其他授权微信帐号";
		}else if(errorCode.equals("-1")) {
			return "系统繁忙";
			
		}else {
			return "未知";
		}		
	}
	
	@Override
	protected void onPause() {
//		JPushInterface.onPause(this);
		super.onPause();
	}
	
	@Override
	public void finish() {
		App.getInstance().getAllActivity().remove(this);
		super.finish();
	}
	@Override
	protected void onDestroy() {
		App.getInstance().getAllActivity().remove(this);
		super.onDestroy();
	}
}
